package com.hec.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.hec.yygh.cmn.listener.DictListener;
import com.hec.yygh.cmn.mapper.DictMapper;
import com.hec.yygh.cmn.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hec.yygh.model.cmn.Dict;
import com.hec.yygh.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author hec
 * @since 2022-10-14
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;



    @Cacheable(value="dict")
    @Override
    public List<Dict> getDictListByPid(Integer parentId) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,parentId);
//        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        List<Dict> dicts = this.list(queryWrapper);
        for (Dict dict : dicts) {
            boolean result = hasChild(dict);
            dict.setHasChildren(result);
        }
        log.info("dicts================"+dicts);
        return dicts;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        try {
            //导出文件的时候，一定要设置两个头信息：Mime-Type、content-type：attachment
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
//            List<Dict> dicts = dictMapper.selectList(null);
            List<Dict> dicts = this.list(null);
            ArrayList<DictEeVo> DictEeVoList = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                DictEeVoList.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet().doWrite(DictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //判断parentDictCode是否为空
        if (StringUtils.isEmpty(parentDictCode)){
            //1、如果为空，就只根据value值查询
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dict::getValue,value);
            Dict dict = dictMapper.selectOne(queryWrapper);
            if (dict != null){
                return dict.getName();
            }
        }else{
            //2、如果不为空，先通过parentDictCode把dict对象查询出来，dict中的id和value查询
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dict::getDictCode,parentDictCode);
            Dict dict = dictMapper.selectOne(queryWrapper);
            Long id = dict.getId();
            String value1 = dict.getValue();
            LambdaQueryWrapper<Dict> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Dict::getId, id);
            queryWrapper1.eq(Dict::getValue, value1);
            Dict dict1 = dictMapper.selectOne(queryWrapper1);
            if(dict1 != null){
                return dict1.getName();
            }
        }


        return null;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = dictMapper.selectOne(queryWrapper);
        Long id = dict.getId();
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId,id);
        List<Dict> dicts = dictMapper.selectList(wrapper);
        return dicts;
    }

    //判断当前元素是否有下一级子元素，有就返回true，没有返回false
    private boolean hasChild(Dict dict) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,dict.getId());
        Integer count = dictMapper.selectCount(queryWrapper);
        return count>0;

    }
}
